package com.MediaVaultTest;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Map;

import javax.persistence.metamodel.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import com.MediaVaultTest.PMF;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class Upload extends HttpServlet {
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

    public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    	String msg = "";
        Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
        Object[] keys = blobs.keySet().toArray();
        for(int i = 0; i < blobs.size(); i++){
        	
	        BlobKey blobKey = blobs.get(keys[i]);
	        
	        if (blobKey == null) {
	        	if(msg=="") msg="no blobs upload";
	            res.sendRedirect("/index.jsp?msg="+msg);
	        } else {
	        	QuotaLogic quotaLogic = new QuotaLogic();
	        	//Setup Quoats
	        	long uploadSize = quotaLogic.getUploadQuota();
	        	long stoargeSize = quotaLogic.getStorageQuota();
	        	
	        	//Setup factories
	       	 	UserService userService = UserServiceFactory.getUserService();
	       	 	User user = userService.getCurrentUser();
	       	 	
	       	 	//Check user loged in 
	       	 	if(user!=null){
		        	 String email =  user.getEmail();
		        	 BlobInfo blobInfo;
		        	 BlobInfoFactory blobInfoFactory = new BlobInfoFactory();
		        	 blobInfo = blobInfoFactory.loadBlobInfo(blobKey);
		        	 
		        	 //Caculate data for object
		        	 Long Size = blobInfo.getSize();
		        	 String mediaType = blobInfo.getContentType();
		        	 String Title = blobInfo.getFilename();
		        	 
		        	 //Add File to user
		        	 PersistenceManager pm = PMF.get().getPersistenceManager();
		    		 UserStore userStore = null;
		    		 Key key = KeyFactory.createKey(UserStore.class.getSimpleName(), email);
		    		 try { 
		    			 //Get the user store and create media file
		    			 userStore = pm.getObjectById(UserStore.class, key);
		    			 if(uploadSize>(userStore.getmbUpload()+Size)&&stoargeSize>(userStore.getmbStorage()+Size)){
			    			 Format format = new Format(blobKey, Size, mediaType);
			    			 Media media = new Media(format, Title);
			    			 //set the key to blob id and attach media file to user
			    			 Key mediaKey = KeyFactory.createKey(Media.class.getSimpleName(), blobKey.getKeyString());
			    			 media.setKey(mediaKey);
			    			 if(format.getHTTPmediaType().contains("image")){
			    				 media.setMediaType("Photo");
			    				 if(blobInfo.getSize()<quotaLogic.getMaxThumbnailSize()){
			    					 media.setCover(blobKey);
			    				 }
			    			 } else if(format.getHTTPmediaType().contains("audio")){
			    				 media.setMediaType("Music");
			    			 } else if(format.getHTTPmediaType().contains("video")){
			    				 media.setMediaType("Movie");
			    			 }
			    			 userStore.addMediaFile(media);
			    			 //update quotas
			    			 userStore.setmbUpload(userStore.getmbUpload()+Size);
			    			 userStore.setmbStorage(userStore.getmbStorage()+Size);
			    			 msg = "Upload succeded";
			    			 res.sendRedirect("/index.jsp?msg="+msg);
		    			 } else {
		    				 //Insufficent data delete file
		    				 msg = "Upload failed, insufficent quota.";
		    				 blobstoreService.delete(blobKey);
		    				 res.sendRedirect("/index.jsp?msg="+msg);
		    			 }
		    		 } finally {
		    			 //Do nothing
		    		 }
		        	pm.close();
	       	 	} else {
	       	 		//User not logged in
	       	 		msg = "Upload failed, user not logged in.";
	       	 		blobstoreService.delete(blobKey);
	       	 		res.sendRedirect("/index.jsp?msg="+msg);
	       	 	}
	       	 	
	        }
       	 
        }
    }
}
